<?php

namespace app\api\controller;

use addons\shopro\controller\Order;
use addons\shopro\model\Goods;
use addons\shopro\model\Store;
use addons\shopro\model\User;
use addons\shopro\model\UserWalletLog;
use app\admin\model\ClinicLog;
use app\admin\model\LevelBuyLog;
use app\admin\model\UserLevelSetting;
use app\common\controller\Api;
use think\Db;
use think\Hook;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1','gouzi'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];


    // 订单支付成功
    public function orderPayedAfter()
    {
        // 订单支付成功
        $params['order']['id'] = 220;
        $order = $params['order'];

        $pay_type[0] = '';
        // 重新查询订单
        $order = \addons\shopro\model\Order::with('item')->where('id', $order['id'])->find();

        //查询是否有门诊店报名的订单
        if ($order['clinc_score_id'] > 0 && $order['activity_type'] == 'activity_baoming') {
            //门诊店报名购买状态修改
            ClinicLog::where(['order_sn' => $order['order_sn'], 'clinc_score_id' => $order['clinc_score_id']])->update(['is_pay' => 1]);
        }
        $items = $order ? $order['item'] : [];

        //判断会员升级专区的商品订单
        if ($order['type'] == "user_level") {
            $user = User::get($order->user_id);
            $goods = Goods::get($items[0]['goods_id']);

            $pay_type = isset($order->pay_type) &&$order->pay_type!==null ? $order->pay_type : 'wallet';
            $data = ['user_id'=>$order->user_id,'type'=>'user_level','goods'=>$goods,'pay_type'=>$pay_type];
           $this->run($data);

//            $user_level_setting = UserLevelSetting::all();
//            $levelIds = array_column($user_level_setting, 'level', 'id');
//            $newULevelSettingAwardScore = array_column($user_level_setting, 'award_score', 'level');
//            $momArr = array_column($user_level_setting, 'mom', 'level');
//
//            $upgrade_level = $levelIds[$goods->user_level_id];
//            if($user->level+1==$upgrade_level){ //第一次购买当前等级//判断是否是复购
//                $up_user_level_setting = UserLevelSetting::where(['id' => $goods->user_level_id])->find();
//                //$user->score += $up_user_level_setting->award_score;
//                //增加会员积分
//                //User::score($up_user_level_setting->award_score, $order->user_id, 'award_score', $order->id, '会员积分商品购买', []);
//
//                $unfreeze_day = config("site.unfreeze_day");
//                $dj_score = 'level' . $upgrade_level . '_dj_score';
//                $current_level = 'level' . $user['level'] . '_dj_score';
//                $pay_type = isset($order->pay_type) &&$order->pay_type!==null ? $order->pay_type : 'wallet';
//                //增加购买记录
//                $level_buy_log = [
//                    'user_id' => $order->user_id,
//                    'level' => $upgrade_level,
//                    'money' => $goods->price,
//                    'type' => $pay_type,
//                    'ctime' => time(),
//                    'award_score' => $newULevelSettingAwardScore[$upgrade_level]
//                ];
//                $buy_log = LevelBuyLog::create($level_buy_log);
//                //购买等级奖励积分
//                User::score(bcmul($newULevelSettingAwardScore[$upgrade_level], $momArr[$upgrade_level]), $order->user_id, 'award_score', $order->id, '等级购买奖励积分', []);
//                //获取等级设置
//                $userLevelSetting = UserLevelSetting::where(['level' => $upgrade_level])->find();
//                //是否有冻结的积分
//                if ($userLevelSetting->freeze_score > 0) {
//                    //每天释放的数量
//                    $days_unfreeze = bcdiv($userLevelSetting->freeze_score, $unfreeze_day);
//                    //写冻结记录表
//                    $score_freeze_log = [
//                        'user_id' => $user->id,
//                        'unfreeze' => $userLevelSetting->freeze_score,
//                        'type' => 1,
//                        'remark' => '用户购买等级' . $userLevelSetting->level . '冻结积分',
//                        'freeze_day' => $unfreeze_day,  //冻结的天数，
//                        'released_day' => 0,
//                        'status' => 1,
//                        'ctime' => time(),
//                        'days_unfreeze' => $days_unfreeze,
//                        'source' => $buy_log->id
//                    ];
//                    Db::name('score_freeze_log')->insert($score_freeze_log);
//                    //增加用户冻结的积分
//                    Db::name('user')->where(['id' => $user->id])->setInc($dj_score, $userLevelSetting->freeze_score);
//                    $before = bcsub($user->score, $user->$current_level, 2);
//                    //购买奖励的积分后 冻结积分
//                    $user_score_log = [
//                        'user_id' => $user->id,
//                        'score' => -$userLevelSetting->freeze_score,
//                        'before' => $before,
//                        'after' => bcsub($before, $userLevelSetting->freeze_score),
//                        'memo' => '会员购买冻结等级' . $upgrade_level . '积分',
//                        'createtime' => time()
//                    ];
//                    Db::name('user_score_log')->insert($user_score_log);
//
//                    //冻结的积分是否解冻
//                    if ($userLevelSetting->unfreeze == 1) {
//                        Db::name('user')->where(['id' => $user->id])->setDec("$current_level", $user->$current_level);
//                        //增加解冻记录
//                        $user_score_log = [
//                            'user_id' => $user->id,
//                            'score' => $user->$current_level,
//                            'before' => $before,
//                            'after' => bcadd($before, $user->$current_level),
//                            'memo' => '冻结的上一级积分解冻',
//                            'createtime' => time()
//                        ];
//                        Db::name('user_score_log')->insert($user_score_log);
//                    }
//                }
//                //达到升级条件
//                $user->level += 1;
//                $user->save();
//            }
        }


        // 有门店相关的订单
        $storeIds = [];
        foreach ($items as $item) {
            if (in_array($item['dispatch_type'], ['store', 'selfetch']) && $item['store_id']) {
                $storeIds[] = $item['store_id'];
            }
        }

        $data = [];
        if ($storeIds) {
            $data = [];
            // 存在门店，查询门店管理员
            $stores = Store::with(['userStore.user'])->where('id', 'in', $storeIds)->select();
            foreach ($stores as $key => $store) {
                $userStoreList = $store['user_store'] ?: [];
                unset($store['user_store']);

                // 当前门店所有用户管理员
                $userList = [];
                foreach ($userStoreList as $user) {
                    if ($user['user']) {
                        $userList[] = $user['user'];
                    }
                }

                // 有用户才能发送消息
                if ($userList) {
                    $data[] = [
                        'store' => $store,
                        'userList' => $userList
                    ];
                }
            }
        }

        // 存在要通知的门店管理员
        if ($data) {
            // 按门店为单位发送通知
            foreach ($data as $key => $sendData) {
                \addons\shopro\library\notify\Notify::send(
                    $sendData['userList'],
                    new \addons\shopro\notifications\store\Order([
                        'store' => $sendData['store'],
                        'order' => $order,
                        'event' => 'store_order_new'
                    ])
                );
            }
        }
    }

    public function run(&$params)
    {

        $user = \addons\shopro\model\User::get($params['user_id']);
        $user_level_setting = UserLevelSetting::all();
        $levelIds = array_column($user_level_setting, 'level', 'id');
        if ($user && $params['type'] == 'invite') {
            //当前用户邀请人数
            $invite_num = \app\common\model\User::where(['pid' => $params['user_id']])->count();
            $new_user_level_setting = array_column($user_level_setting, 'invite_upgrade_num', 'level');

            if (isset($new_user_level_setting[$user['level'] + 1]) && $invite_num >= $new_user_level_setting[$user['level'] + 1]) {

                $params['memo'] = '邀请会员升级';
                $params['pay_type'] = 'invite';
                $this->upgrade($user_level_setting, $user, $params);
            }
        } else if ($user->level+1==$levelIds[$params['goods']['user_level_id']] && $params['type'] == 'user_level') {    //会员专区升级商品

            $params['memo'] = '会员专区商品购买升级';
            $this->upgrade($user_level_setting, $user, $params);
        }
    }

    //升级
    public function upgrade($user_level_setting, $user, $params)
    {
        $newULevelSettingAwardScore = array_column($user_level_setting, 'award_score', 'level');
        $momArr = array_column($user_level_setting, 'mom', 'level');
        $upgrade_level = $user['level'] + 1;
        $unfreeze_day = config("site.unfreeze_day");
        $dj_score = 'level' . $upgrade_level . '_dj_score';
        $current_level = 'level' . $user['level'] . '_dj_score';
        //增加购买记录
        $level_buy_log = [
            'user_id' => $user->id,
            'level' => $upgrade_level,
            'money' => isset($params['goods']['price'])?$params['goods']['price']:0,
            'type' => $params['pay_type'],
            'ctime' => time(),
            'award_score' => $newULevelSettingAwardScore[$upgrade_level]
        ];
        $buy_log = LevelBuyLog::create($level_buy_log);
        //购买等级奖励积分
        \addons\shopro\model\User::score(bcmul($newULevelSettingAwardScore[$upgrade_level], $momArr[$upgrade_level]), $user->id, 'award_score', 0, $params['memo'] . '奖励积分', []);

        //获取等级设置
        $userLevelSetting = UserLevelSetting::where(['level' => $upgrade_level])->find();
        //是否有冻结的积分
        if ($userLevelSetting->freeze_score > 0) {
            //每天释放的数量
            $days_unfreeze = bcdiv($userLevelSetting->freeze_score, $unfreeze_day);
            //写冻结记录表
            $score_freeze_log = [
                'user_id' => $user->id,
                'unfreeze' => $userLevelSetting->freeze_score,
                'type' => $params['type']=='user_level'?1:2,
                'remark' => $params['memo'] . '等级' . $userLevelSetting->level . '冻结积分',
                'freeze_day' => $unfreeze_day,  //冻结的天数，
                'released_day' => 0,
                'status' => 1,
                'level' => $upgrade_level,
                'ctime' => time(),
                'days_unfreeze' => $days_unfreeze,
                'source' => $buy_log->id
            ];
            Db::name('score_freeze_log')->insert($score_freeze_log);
            //增加用户冻结的积分
            Db::name('user')->where(['id' => $user->id])->setInc($dj_score, $userLevelSetting->freeze_score);
            $before = bcsub($user->score, $user->$current_level, 2);
            //购买奖励的积分后 冻结积分
            $user_score_log = [
                'user_id' => $user->id,
                'score' => $userLevelSetting->freeze_score,
                'before' => $before,
                'after' => bcsub($before, $userLevelSetting->freeze_score),
                'memo' => $params['memo'] . '冻结等级' . $upgrade_level . '积分',
                'createtime' => time()
            ];
            Db::name('user_score_log')->insert($user_score_log);
            UserWalletLog::write($user, $userLevelSetting->freeze_score, $before, bcsub($before, $userLevelSetting->freeze_score), "freeze", $buy_log->id, "score", $params['memo'] . '冻结等级' . $upgrade_level . '积分', []);
            $list = Db::name('score_freeze_log')->where(['user_id'=>$user->id,'level'=>$user->level])->select();
            if($list){
                foreach ($list as $k=>$v){
                    Db::name('score_freeze_log')->where(['id'=>$v['id']])->update(['is_unfreeze'=>1]);
                }
            }
            //冻结的积分是否解冻
            //if ($userLevelSetting->unfreeze == 1) {
            //Db::name('user')->where(['id' => $user->id])->setDec("$current_level", $user->$current_level);
            //增加解冻记录
//                $user_score_log = [
//                    'user_id' => $user->id,
//                    'score' => $user->$current_level,
//                    'before' => $before,
//                    'after' => bcadd($before, $user->$current_level),
//                    'memo' => '冻结的上一级积分解冻',
//                    'createtime' => time()
//                ];
//                Db::name('user_score_log')->insert($user_score_log);
            //Db::name('user')->where(['id' => $user->id])->setInc("score", $user->$current_level);
            //UserWalletLog::write($user, $user->$current_level, $before, bcadd($before, $user->$current_level), "unfreeze", $buy_log->id, "score", "冻结的上一级积分解冻", []);
            //解冻后删除对应用户对应等级的待释放积分
            //$list = Db::name('score_freeze_log')->where(['user_id'=>$user->id,'level'=>$user->level])->select();
            //                if($list){
            //                    foreach($list as $k=>$v){
            //                        Db::name('score_freeze_log')->where(['id'=>$v['id']])->update(['status'=>0]);
            //                    }
            //                }
            //}
        }
        $user->level += 1;
        $user->save();
    }

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */

    public function test()
    {
        //购买会员专区商品升级
        $ordermodel = new \addons\shopro\model\Order();
        $id = input('id');
        $order = $ordermodel::get($id);

        $data['order'] = $order;
        \think\Hook::listen('order_payed_after', $data);
        $this->success('返回成功', $this->request->param());
    }
    //邀请会员升级
    public function gouzi()
    {
        // 注册 app\index\behavior\CheckLang行为类到app_init标签位
        $data = ['user_id'=>$this->auth->id,'type'=>'invite'];
        \think\Hook::listen('user_upgrade',$data);
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $ordermodel = new \addons\shopro\model\Order();
        $id = input('id');
        $order = $ordermodel::get($id);
        $user = \app\admin\model\User::get(10);
        \think\Queue::push('\addons\shopro\job\OrderPayed@payed', ['order' => $order, 'user' => $user], 'shopro-high');

        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

}
